import serial  # 导入模块
import threading
import time
STRGLO = ""  # 读取的数据
BOOL = True  # 读取标志位


# 读数代码本体实现
def ReadData():
    global STRGLO, BOOL
    # 循环接收数据，此为死循环，可用线程实现
    readData = '';
    while True:
        count = ser.inWaiting()
        if count > 0:
            STRGL1 = ser.read(count).decode("gbk")
            if STRGL1 != b'':
                readData += str(STRGL1)
                # print("读数据:", readData)
                if readData == '10$':
                    print("连接成功:", readData)
                    readData = '';
                    DWritePort("60$")
                elif readData == '11$':
                    print("准备测量:", readData)
                    readData = '';
                    DWritePort("11$")
                    print("暂停5秒发送测量数据:", readData)
                    time.sleep(5)
                    DWritePort('W:075.9 H:180.5\r\n')
                else:
                    print("其他数据:", readData)
            else:
                ser.write(hexsend(STRGL1))


# 打开串口
# 端口，GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
# 波特率，标准值之一：50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
# 超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
def DOpenPort(portx, bps, timeout):
    global ser
    ret = False
    try:
        # 打开串口，并得到串口对象
        ser = serial.Serial(portx, bps, timeout=timeout)
        # 判断是否打开成功
        if ser.is_open:
            ret = True
            threading.Thread(target=ReadData, args=()).start()
    except Exception as e:
        print("---异常---：", e)
    return ser, ret


# 关闭串口
def DColsePort(ser):
    global BOOL
    BOOL = False
    ser.close()


# 写数据
def DWritePort(text):
    print("写数据：", text)
    result = ser.write(text.encode("gbk"))  # 写数据
    return result


# 读数据
def DReadPort():
    global STRGLO
    str = STRGLO
    STRGLO = ""  # 清空当次读取
    return str


if __name__ == "__main__":
    ser, ret = DOpenPort("COM8", 9600, None)

    if ret:  # 判断串口是否成功打开
        # count = DWritePort(ser, "$1")
        count = DWritePort('W:075.9 H:180.5\r\n')
        print("写入字节数：", count)
        # DReadPort() #读串口数据
        # DColsePort(ser)  #关闭串口
